package org.bonorsoft.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.constant.CacheConstant;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.modules.system.entity.SysConfig;
import org.bonorsoft.modules.system.mapper.SysConfigMapper;
import org.bonorsoft.modules.system.service.ISysConfigService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 系统配置
 * @Author: WilliamYe
 * @Date:   2020-12-02
 * @Version: V1.0
 */
@Service
@Slf4j
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config)
    {
        Integer configId = StringUtils.isNull(config.getConfigId()) ? -1 : config.getConfigId();
        SysConfig info = getConfigInfo(config.getConfigKey());
        if (StringUtils.isNotNull(info) && !info.getConfigId().equals(configId))
        {
            return UserConstants.CONFIG_KEY_NOT_UNIQUE;
        }
        return UserConstants.CONFIG_KEY_UNIQUE;
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    @Cacheable(value = CacheConstant.SYS_CONFIG_CACHE, key = "#configKey")
    public String selectConfigByKey(String configKey) {
        log.info("无系统配置缓存");
        SysConfig info = getConfigInfo(configKey);
        return info.getConfigValue();
    }

    /**
     * 清空缓存数据
     */
    @Override
    @CacheEvict(value = CacheConstant.SYS_CONFIG_CACHE, allEntries = true)
    public void clearCache()
    {
    }

    /**
     * 根据key值获取配置信息
     * @param configKey
     * @return
     */
    private SysConfig getConfigInfo(String configKey) {
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_key", configKey);
        return this.getOne(queryWrapper);
    }

}
